package f_graph_basics.b_read_graph_from_file;

import f_graph_basics.a_graph_representation.DenseGraph;
import f_graph_basics.a_graph_representation.Graph;
import f_graph_basics.a_graph_representation.SparseGraph;
import org.junit.platform.commons.util.StringUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class ReadGraph {

    /**
     * 读取文本文件数据 对现有图进行连线
     * @param g 现有图 支持稀疏图和稠密图
     *          要求现有图的节点数大于等于数据中的节点数
     * @param filePath 文件路径
     * @return 覆盖连线的新图
     *
     * 文本数据格式说明 每行两个数字中间一个空格分割
     * 第一行的两个数字分别代表数据中的节点和边的数量
     * 第二行开始分别代表连线的两个节点
     */
    public static Graph readGraph(Graph g, String filePath) throws Exception {
        int v;
        int e = 0;
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        try {
            List<String> lines = Files.readAllLines(Paths.get(filePath));
            String headline = lines.get(0);
            if (!headline.isEmpty()) {
                String[] split = headline.split(" ");
                if (split.length == 2) {
                    v = Integer.parseInt(split[0]);
                    e = Integer.parseInt(split[1]);
                    assert g.v() >= v;
                    assert e == lines.size() - 1;
                }
            }
            for (int i = 1; i <= e; i++) {
                String line = lines.get(i);
                if (!line.isEmpty()) {
                    String[] split = line.split(" ");
                    if (split.length == 2) {
                        int m = Integer.parseInt(split[0]);
                        int n = Integer.parseInt(split[1]);
                        g.addEdge(m, n);
                    } else {
                        throw new Exception("数据格式错误, 要求每行两个数字且用一个空格分隔！");
                    }
                }
            }
        } catch (IOException exception) {
            exception.printStackTrace();
        }
        return g;
    }

    public static void main(String[] args) throws Exception {
        String rootPath = ReadGraph.class.getResource("").getPath().substring(1);
        Graph g1 = new DenseGraph(13, false);
        g1 = readGraph(g1, rootPath + "testG1.txt");
        assert g1 != null;
        g1.testPrint();
        System.out.println("=========================");
        Graph g2 = new SparseGraph(6, false);
        g2 = readGraph(g2, rootPath + "testG2.txt");
        assert g2 != null;
        g2.testPrint();
    }

}
